<template>
  <div class="my-exam-record-detail-container">
    <el-card shadow="never" v-loading="isLoading">
      <template #header>
        <div class="card-header">
          <span>考试结果详情 (考试 ID: {{ examId }})</span>
          <el-button style="margin-left: auto;" @click="goBack">返回列表</el-button>
        </div>
      </template>

       <div v-if="errorMsg">
          <el-alert type="error" :title="errorMsg" show-icon :closable="false"></el-alert>
       </div>
       
      <div v-else-if="recordDetail">
          <!-- 考试基本信息 -->
          <el-descriptions :title="recordDetail.examInfo?.title || '考试信息'" :column="3" border class="exam-info-section">
                <el-descriptions-item label="总分">{{ recordDetail.examInfo?.totalScore ?? '-' }}</el-descriptions-item>
                <el-descriptions-item label="及格分">{{ recordDetail.examInfo?.passScore ?? '-' }}</el-descriptions-item>
                <el-descriptions-item label="提交时间">{{ formatDateTime(recordDetail.examRecord?.submitTime) }}</el-descriptions-item>
                <el-descriptions-item label="你的得分">
                    <el-tag :type="recordDetail.examRecord?.passed ? 'success' : 'danger'" size="large">
                        {{ recordDetail.examRecord?.score?.toFixed(1) ?? '-' }}
                    </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="是否通过">
                     <el-tag v-if="recordDetail.examRecord?.passed !== null" :type="recordDetail.examRecord?.passed ? 'success' : 'danger'" size="large">
                        {{ recordDetail.examRecord?.passed ? '通过' : '未通过' }}
                    </el-tag>
                    <span v-else>-</span>
                </el-descriptions-item>
                 <el-descriptions-item label="状态">
                     <el-tag :type="getRecordStatusTagType(recordDetail.examRecord?.status)">{{ getRecordStatusText(recordDetail.examRecord?.status) }}</el-tag>
                 </el-descriptions-item>
            </el-descriptions>
            
            <el-divider></el-divider>
            
            <h3>答题详情与批改结果</h3>
            
            <div v-if="examQuestions && examQuestions.length > 0">
                 <div v-for="(question, index) in examQuestions" :key="question.id" class="question-result-block">
                     <p><strong>{{ index + 1 }}. [{{ formatQuestionType(question.type) }} - {{ question.score?.toFixed(1) }}分]</strong> {{ question.content }}</p>
                     
                     <p>你的答案: <el-tag>{{ displayAnswer(studentAnswersMap[question.id]) }}</el-tag></p>
                     
                     <p v-if="shouldShowCorrectAnswer(question.type)">
                       正确答案: <el-tag type="success">{{ displayAnswer(question.answers) }}</el-tag>
                     </p>

                     <div v-if="scoreResultsMap && scoreResultsMap[question.id]">
                         <p>得分: 
                             <el-tag :type="getScoreTagType(scoreResultsMap[question.id].score, question.score)">
                                 {{ scoreResultsMap[question.id].score?.toFixed(1) ?? '-' }}
                             </el-tag>
                         </p>
                         <p v-if="scoreResultsMap[question.id].comments">教师评语: <span class="comment-text">{{ scoreResultsMap[question.id].comments }}</span></p>
                     </div>
                     <div v-else>
                         <p><el-tag type="info">无评分记录</el-tag></p>
                     </div>
                 </div>
                 
                 <el-divider></el-divider>
                 <h4>分数汇总</h4>
                  <el-descriptions :column="2" border >
                     <el-descriptions-item label="客观题得分">{{ recordDetail.scoringDetails.autoGradedTotal?.toFixed(1) ?? '-' }}</el-descriptions-item>
                     <el-descriptions-item label="主观题得分">{{ recordDetail.scoringDetails.manualGradedTotal?.toFixed(1) ?? '-' }}</el-descriptions-item>
                     <el-descriptions-item label="最终总得分">
                         <el-tag type="danger" size="large">{{ recordDetail.scoringDetails.finalTotalScore?.toFixed(1) ?? '-' }}</el-tag>
                     </el-descriptions-item>
                  </el-descriptions>
                 
            </div>
            <el-alert v-else-if="recordDetail.examRecord?.status === 'SUBMITTED'" title="试卷尚未批改完成" type="info" show-icon :closable="false"></el-alert>
            <el-empty v-else description="无法加载评分详情"></el-empty>
            
      </div>
      <el-empty v-else description="暂无考试记录详情"></el-empty>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getStudentExamRecordDetail, getStudentRecordDetailForTeacher } from '@/services/examService';
import { ElCard, ElButton, ElTag, ElDescriptions, ElDescriptionsItem, ElDivider, ElEmpty, ElAlert } from 'element-plus';

const route = useRoute();
const router = useRouter();

const examId = ref(route.params.examId);
const studentIdForTeacherView = ref(route.query.studentId);

const recordDetail = ref(null);
const examQuestions = ref([]);
const scoreResultsMap = ref({});
const studentAnswersMap = ref({});
const isLoading = ref(false);
const errorMsg = ref('');

const loadRecordDetail = async () => {
    if (!examId.value) {
        errorMsg.value = '无效的考试ID';
        return;
    }
    isLoading.value = true;
    errorMsg.value = '';
    // Clear previous data
    recordDetail.value = null;
    examQuestions.value = [];
    scoreResultsMap.value = {};
    studentAnswersMap.value = {};
    try {
        let response;
        if (studentIdForTeacherView.value) {
            console.log(`Teacher view detected. Fetching record for exam ${examId.value}, student ${studentIdForTeacherView.value}`);
            response = await getStudentRecordDetailForTeacher(examId.value, studentIdForTeacherView.value);
        } else {
            console.log(`Student view detected. Fetching record for exam ${examId.value}`);
            response = await getStudentExamRecordDetail(examId.value);
        }
        
        if (response && response.success && response.data) {
            recordDetail.value = response.data;
            
            if (Array.isArray(response.data.questions)) {
                examQuestions.value = response.data.questions.sort((a, b) => (a.order ?? a.id) - (b.order ?? b.id));
            } else {
                examQuestions.value = [];
                console.warn("API response missing or invalid 'questions' array.");
            }

            if (response.data.examRecord?.answers) {
                try {
                    studentAnswersMap.value = JSON.parse(response.data.examRecord.answers);
                } catch (e) {
                    console.error("Failed to parse student answers JSON:", e);
                    studentAnswersMap.value = {};
                }
            } else {
                studentAnswersMap.value = {};
                console.warn("API response missing 'examRecord.answers'.");
            }

            const tempScoreMap = {};
            const scoringDetails = response.data.scoringDetails;

            if (scoringDetails) {
                if (Array.isArray(scoringDetails.autoGradedQuestions)) {
                    scoringDetails.autoGradedQuestions.forEach(scoreData => {
                        if (scoreData && scoreData.questionId !== undefined) {
                           tempScoreMap[scoreData.questionId] = scoreData;
                        }
                    });
                }
                 if (Array.isArray(scoringDetails.pendingQuestions)) {
                     scoringDetails.pendingQuestions.forEach(scoreData => {
                         if (scoreData && scoreData.questionId !== undefined) {
                            tempScoreMap[scoreData.questionId] = scoreData;
                         }
                    });
                }
                 if (Array.isArray(scoringDetails.questionScores)) {
                     scoringDetails.questionScores.forEach(scoreData => {
                         if (scoreData && scoreData.questionId !== undefined) {
                            tempScoreMap[scoreData.questionId] = scoreData;
                         }
                     });
                 }
            } else {
                console.warn("API response missing 'scoringDetails'.");
            }
            
            scoreResultsMap.value = tempScoreMap;
            
            // --- Frontend Calculation Fallback --- 
            // If summary scores are missing from API, calculate them here
            if (recordDetail.value && recordDetail.value.scoringDetails) {
                const details = recordDetail.value.scoringDetails;
                if (details.autoGradedTotal === undefined || details.manualGradedTotal === undefined || details.finalTotalScore === undefined) {
                    console.warn("Scoring summary fields missing from API, calculating in frontend.");
                    
                    let calculatedAuto = 0;
                    let calculatedManual = 0;
                    
                    // Calculate from scoreResultsMap (built from autoGraded, pending, questionScores)
                    Object.values(scoreResultsMap.value).forEach(scoreData => {
                        // Find the original question to check its type and maxScore
                        const originalQuestion = examQuestions.value.find(q => q.id === scoreData.questionId);
                        if (!originalQuestion) return; 

                        const score = scoreData.score ?? 0;
                        // Determine if it *should* have been auto-graded based on type
                        if (['SINGLE_CHOICE', 'MULTIPLE_CHOICE', 'TRUE_FALSE'].includes(originalQuestion.type)) {
                             calculatedAuto += score;
                        } else { // Assume others are manually graded
                             calculatedManual += score;
                        }
                    });

                    // Assign calculated values ONLY IF they are missing
                    if (details.autoGradedTotal === undefined) {
                        details.autoGradedTotal = calculatedAuto;
                    }
                    if (details.manualGradedTotal === undefined) {
                        details.manualGradedTotal = calculatedManual;
                    }
                    // Always recalculate final score based on potentially supplemented values
                    details.finalTotalScore = (details.autoGradedTotal ?? 0) + (details.manualGradedTotal ?? 0);
                    
                    console.log("Frontend calculated/supplemented scoring summary:", details);
                }
            }
            // ------------------------------------

            // 添加日志，检查最终的 scoringDetails 内容
            console.log("Final scoringDetails used by template:", recordDetail.value?.scoringDetails);

        } else {
            errorMsg.value = response?.message || '加载考试记录详情失败';
            recordDetail.value = null;
            examQuestions.value = [];
            scoreResultsMap.value = {};
            studentAnswersMap.value = {};
        }
    } catch (error) {
        console.error("Error fetching exam record detail:", error);
        errorMsg.value = '加载数据时发生网络或未知错误';
        recordDetail.value = null;
        examQuestions.value = [];
        scoreResultsMap.value = {};
        studentAnswersMap.value = {};
    } finally {
        isLoading.value = false;
    }
};

// --- Helper Functions ---
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '-';
  try { return new Date(dateTimeString).toLocaleString(); } catch (e) { return dateTimeString; }
};
const getRecordStatusText = (status) => {
  const map = { SUBMITTED: '已提交', MARKED: '已批改' };
  return map[status] || status;
};
const getRecordStatusTagType = (status) => {
  const map = { SUBMITTED: 'primary', MARKED: 'success' };
  return map[status] || 'info';
};
const formatQuestionType = (type) => {
  const typeMap = { SINGLE_CHOICE: '单选', MULTIPLE_CHOICE: '多选', TRUE_FALSE: '判断', FILL_BLANK: '填空', SHORT_ANSWER: '简答' };
  return typeMap[type] || type;
};
const displayAnswer = (answer) => {
    if (answer === null || answer === undefined) {
        return '-'; // 处理 null 或 undefined
    }
    if (Array.isArray(answer)) {
        if (answer.length === 0) {
            return '-'; // 处理空数组
        }
        return answer.join(', ');
    }
    return String(answer); // 其他情况转字符串
};
const shouldShowCorrectAnswer = (type) => {
    return ['SINGLE_CHOICE', 'MULTIPLE_CHOICE', 'TRUE_FALSE'].includes(type);
};
const getScoreTagType = (score, maxScore) => {
    if (score === null || score === undefined) return 'info';
    if (score === maxScore) return 'success';
    if (score > 0) return 'warning';
    return 'danger';
};
// -----------------------

const goBack = () => {
    router.push({ name: 'MyExamRecords' }); // 返回到记录列表页
};

onMounted(() => {
    loadRecordDetail();
});

</script>

<style scoped>
.my-exam-record-detail-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.exam-info-section {
    margin-bottom: 20px;
}
.question-result-block {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e9ecef;
  border-radius: 4px;
}
.question-result-block p {
  margin-bottom: 8px;
}
.comment-text {
    color: #e6a23c; /* 橙色突出显示评语 */
    font-style: italic;
}
</style> 